package com.demo.function.thread.jdk;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;

import java.util.concurrent.TimeUnit;

/**
 * 官方的建议：虚拟线程永远都不应该被池化。
 * <a href="https://openjdk.org/jeps/425">官方虚拟线程介绍</a>
 */
@Slf4j
public class VirtualThread {

    public void virtualThread() throws InterruptedException {
        for (int i = 0; i < 10; i++) {
            int temp = i;
            Thread.ofVirtual().name("virtual").start(() -> {
                try {
                    long randomTime = RandomUtils.nextLong(1, 1000);
                    TimeUnit.MILLISECONDS.sleep(randomTime);
                    log.info("当前线程：{}，randomTime = {}，i = {}", Thread.currentThread(), randomTime, temp);
                } catch (InterruptedException e) {
                    log.error("", e);
                }
            });
        }

        TimeUnit.SECONDS.sleep(10);
        log.info("主线程结束");
    }
}
